package com.example.watchcat2k.finalproject;

import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.AttributeSet;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.POST;

public class FindFragment extends Fragment {

    TextView update;
    GridView gridview_user_by_recommend1;
    private User_basic_info my_info;
    private MyGridViewAdapter myGridViewAdapter;
    Boolean first = true;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_find, container, false);

        update = view.findViewById(R.id.textView16);
        gridview_user_by_recommend1 = view.findViewById(R.id.find_user_by_recommend1);


        Bundle bundle = getArguments();
        my_info = (User_basic_info) bundle.get("user");




        myGridViewAdapter = new MyGridViewAdapter(view.getContext());


        require_user();

        setclick();



        return view;
    }


    void setclick(){

        //更新
        update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                require_user();
            }
        });


        //点击进入个人主页
        gridview_user_by_recommend1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                User_basic_info info = new User_basic_info(myGridViewAdapter.all_datas.get(position).getUsername(), myGridViewAdapter.all_datas.get(position).getName(),
                        myGridViewAdapter.all_datas.get(position).getDescription(), myGridViewAdapter.all_datas.get(position).getIcon());
                Intent intent = new Intent(view.getContext(), User_Info_Activity.class);
                intent.putExtra("user", info);
                intent.putExtra("username1", my_info.getUsername());
                startActivity(intent);
            }
        });



    }
    void require_user(){
        try {
            OkHttpClient build = new OkHttpClient.Builder()
                    .connectTimeout(2, TimeUnit.SECONDS)
                    .readTimeout(2, TimeUnit.SECONDS)
                    .writeTimeout(2, TimeUnit.SECONDS)
                    .build();

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://129.204.116.253:8080")

                    .addConverterFactory(GsonConverterFactory.create())

                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())//新的配置

                    // build 即为okhttp声明的变量，下文会讲
                    .client(build)

                    .build();

            only_username username = new only_username(my_info.getUsername());
            ServicerecommendUser service = retrofit.create(ServicerecommendUser.class);
            service.postRegister(username)
                    .subscribeOn(Schedulers.io())//请求在新的线程中执行
                    .observeOn(AndroidSchedulers.mainThread())         //请求完成后在主线程中执行
                    .subscribe(new DisposableObserver<find_users_packet>() {
                        @Override
                        public void onNext(find_users_packet find_users_packet_) {
                            myGridViewAdapter.update_datas(find_users_packet_.getAll_users());
                            gridview_user_by_recommend1.setAdapter(myGridViewAdapter);
                            Log.i("数据长度：", "length: " + find_users_packet_.getAll_users().size());
                            /*if(first){
                                setGridViewHeightBasedOnChildren(gridview_user_by_recommend1);
                                gridview_user_by_recommend1.setAdapter(myGridViewAdapter);
                                first = false;
                            }
                            else {
                                myGridViewAdapter.notifyDataSetChanged();
                            }
                            */


                        }

                        @Override
                        public void onError(Throwable e) {
                            Log.i("服务器报错：", "onError: "+e.toString());
                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }catch (Exception o){
            Log.i("异常：", "onError: "+o.toString());
        }
    }

    public class MyGridViewAdapter extends BaseAdapter{
        ArrayList<find_users_packet.users> all_datas;
        Context context;
        ImageView user_icon;
        TextView name;
        TextView user_description;

        public MyGridViewAdapter(Context context){
            this.all_datas = new ArrayList<>();
            this.context = context;
        }

        public void update_datas(ArrayList<find_users_packet.users> new_datas){
            this.all_datas = new_datas;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                convertView = LayoutInflater.from(context).inflate(R.layout.item_search_user, null);
            }

            //绑定
            name = (TextView)convertView.findViewById(R.id.textView_search_username);
            user_description = convertView.findViewById(R.id.textView_search_summary);
            user_icon = convertView.findViewById(R.id.imageView_search_image);

            //填充数据
            name.setText(all_datas.get(position).getName());

            //要判断个人描述是不是太长，太长的话用...
            String description = all_datas.get(position).getDescription();
            if(description.length() < 10){
                user_description.setText(description);
            }
            else {
                String new_description = description.substring(0, 7);
                new_description += "...";
                user_description.setText(new_description);
            }

            byte[] bytes = Base64.decode(all_datas.get(position).getIcon(), Base64.DEFAULT);
            Bitmap bm = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            user_icon.setImageBitmap(bm);

            return convertView;
        }



        @Override
        public int getCount() {
            if(all_datas == null){
                return 0;
            }
            else{
                return all_datas.size();
            }

        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public Object getItem(int position) {
            return all_datas.get(position);
        }
    }


    //重写GridView，解决只出现一行的问题
    public class MyGridView extends GridView {
        public MyGridView(Context context) {
            super(context);
        }
        public MyGridView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);
            super.onMeasure(widthMeasureSpec, expandSpec);
        }
    }



    //解决Gridview只显示一行的错误，动态获取长度
    public static void setGridViewHeightBasedOnChildren(GridView gridView) {
        // 获取GridView对应的Adapter
        ListAdapter myGridViewAdapter = gridView.getAdapter();
        if (myGridViewAdapter == null) {
            return;
        }
        int rows;
        int columns = 0;
        int horizontalBorderHeight = 0;
        Class<?> clazz = gridView.getClass();
        try {
            // 利用反射，取得每行显示的个数
            Field column = clazz.getDeclaredField("mRequestedNumColumns");
            column.setAccessible(true);
            columns = (Integer) column.get(gridView);
            // 利用反射，取得横向分割线高度
            Field horizontalSpacing = clazz
                    .getDeclaredField("mRequestedHorizontalSpacing");
            horizontalSpacing.setAccessible(true);
            horizontalBorderHeight = (Integer) horizontalSpacing.get(gridView);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
        // 判断数据总数除以每行个数是否整除。不能整除代表有多余，需要加一行
        if (myGridViewAdapter.getCount() % columns > 0) {
            rows = myGridViewAdapter.getCount() / columns + 1;
        } else {
            rows = myGridViewAdapter.getCount() / columns;
        }
        int totalHeight = 0;
        for (int i = 0; i < rows; i++) { // 只计算每项高度*行数
            View listItem = myGridViewAdapter.getView(i, null, gridView);
            listItem.measure(0, 0); // 计算子项View 的宽高
            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight + horizontalBorderHeight * (rows - 1);// 最后加上分割线总高度
        gridView.setLayoutParams(params);
    }



    public interface ServicerecommendUser{
        @POST("/recommendUser")
        Observable<find_users_packet> postRegister(@Body only_username only_username_);
    }
}
